package com.pet.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.pet.exceptions.BusinessException;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class HttpUtil {

    private static CloseableHttpClient httpClient = HttpClients.custom().build();

    /**
     * 请求以POST方式
     * @param url 美团的接口url
     * @param applicationParamsMap 参数列表
     * @return
     */
    private static String requestOfPost(String url, Map<String,String> applicationParamsMap){
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //设置参数
            List<BasicNameValuePair> nameValuePairList = ConvertUtil.convertToEntity(applicationParamsMap);
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairList,"UTF-8");
            httpPost.setConfig(getRequestConfig().build());
            httpPost.setEntity(uefEntity);
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            httpPost.releaseConnection();
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                //ignore
            }
        }

    }

    /**
     * 请求以POST方式
     * @param url 美团的接口url
     * @param applicationParamsMap 参数列表
     * @return
     */
    private static String requestOfPost(String url, Map<String,String> applicationParamsMap, byte[] fileData,
                                        String imgName) {
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpResponse response = null;
        try {
            //设置参数
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            List<BasicNameValuePair> nameValuePairList = ConvertUtil.convertToEntity(applicationParamsMap);
            nameValuePairs.addAll(nameValuePairList);

            MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
            ByteArrayBody byteArray = new ByteArrayBody(fileData, imgName);
            entityBuilder.addPart("file", byteArray);

            URLEncodedUtils.format(nameValuePairs, "UTF-8");
            Iterator<NameValuePair> it = nameValuePairs.iterator();
            while(it.hasNext()){
                NameValuePair param = it.next();
                entityBuilder.addPart(param.getName(), new StringBody(param.getValue(), ContentType.TEXT_PLAIN));
            }

            httpPost.setEntity(entityBuilder.build());
            httpPost.setConfig(getRequestConfig().build());
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            return EntityUtils.toString(responseEntity, "UTF-8");
        } catch (Exception e) {
            throw new BusinessException(e);
        }finally {
            httpPost.releaseConnection();
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                //ignore
            }
        }

    }

    /**
     * 请求以GET方式
     * @param url
     * @return
     */
    public static String requestOfGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader(HTTP.CONTENT_TYPE, "application/json");
        httpGet.setConfig(getRequestConfig().build());
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            throw new BusinessException(e);
        }finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpGet.releaseConnection();
            } catch (IOException e) {
                //ignore
            }
        }

    }

    private static RequestConfig.Builder getRequestConfig() {
        RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
        requestConfigBuilder.setConnectTimeout(5000);
        requestConfigBuilder.setConnectionRequestTimeout(3000);
        requestConfigBuilder.setSocketTimeout(3000);
        return requestConfigBuilder;
    }

    /**
     * 请求批量以POST方式
     * @param url 美团的接口url
     * @param applicationParamsList 参数列表
     * @return 请求结果
     */
    public static String requestOfPost(String url, List<Map<String,Object>> applicationParamsList){
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String jsonstr = JSON.toJSONString(applicationParamsList);
        CloseableHttpResponse response = null;
        try {
            //设置参数
            StringEntity se = new StringEntity(jsonstr);
            se.setContentType("text/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(se);
            httpPost.setConfig(getRequestConfig().build());
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            return EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            throw new BusinessException(e);
        }finally {
            httpPost.releaseConnection();
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                //ignore
            }
        }
    }

}
